package com.alex.chat;

import java.io.IOException;
import java.util.Collections;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.Header;

import com.alex.utils.http.HttpClientFactory;
import com.alex.utils.http.HttpResult;
import com.alex.utils.http.RequestBuilder;
import com.alex.utils.http.RequestBuilderFactory;

@WebServlet(urlPatterns = {"/*"})
public class ProxyServlet extends HttpServlet {
	
	static {
		HttpClientFactory httpClientFactory = new HttpClientFactory();
		httpClientFactory.setThreadSafe(true);
		
		REQUEST_BUILDER_FACTORY = new RequestBuilderFactory(httpClientFactory.create());
	}
	
	private static final RequestBuilderFactory REQUEST_BUILDER_FACTORY;
	
	private static final String SOURCE_SITE = "http://xxvideotube.com";
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url = SOURCE_SITE + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		}
		RequestBuilder builder = REQUEST_BUILDER_FACTORY.get(url);
		for (String name : Collections.list(request.getHeaderNames())) {
			for (String header : Collections.list(request.getHeaders(name))) {
				response.addHeader(name, header);
			}
		}
		
		HttpResult httpResult = builder.getResult();
		for (Header header : httpResult.getResponse().getAllHeaders()) {
			response.addHeader(header.getName(), header.getValue());
		}
		response.getOutputStream().write(httpResult.getResponseBodyAsByteArray());
	}

}
